<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Architecture_Components  LiveData 学习 | yangchaojiang</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
    <meta name="keywords" content="yangjiang,yangjiang Blog" />
  
  <meta name="description" content="LiveDataLiveData是数据保持器类的值和运算。不像常规可见，LiveData该生命周期的应用程序组件，使得遵守者可以指定Lifecycle它在哪应注意观察。 注：实时为您导入Android项目添加组件你的项目。">
<meta name="keywords" content="Architecture_Components,LiveData">
<meta property="og:type" content="article">
<meta property="og:title" content="Architecture_Components  LiveData 学习">
<meta property="og:url" content="http://yangchaojiang.cn/2017/06/05/livedata-blog/index.html">
<meta property="og:site_name" content="yangchaojiang">
<meta property="og:description" content="LiveDataLiveData是数据保持器类的值和运算。不像常规可见，LiveData该生命周期的应用程序组件，使得遵守者可以指定Lifecycle它在哪应注意观察。 注：实时为您导入Android项目添加组件你的项目。">
<meta property="og:updated_time" content="2017-06-06T10:59:13.007Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Architecture_Components  LiveData 学习">
<meta name="twitter:description" content="LiveDataLiveData是数据保持器类的值和运算。不像常规可见，LiveData该生命周期的应用程序组件，使得遵守者可以指定Lifecycle它在哪应注意观察。 注：实时为您导入Android项目添加组件你的项目。">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css">
  <script src="/js/pace.min.js"></script>
  

  
  

</head>

<body>
  <div id="container">
      <header id="header">
    <div id="banner"></div>
    <div id="header-outer">
        <div id="header-menu" class="header-menu-pos animated">
            <div class="header-menu-container">
                <a href="/" class="left">
                    <span class="site-title">杨 江</span>
                </a>
                <nav id="header-menu-nav" class="right">
                    
                    <a target="_blank" href="//yanganan.cn">
                        <i class="fa fa-home"></i>
                        <span>Home</span>
                    </a>
                    
                    <a  href="/archives">
                        <i class="fa fa-archive"></i>
                        <span>Archives</span>
                    </a>
                    
                    <a target="_blank" href="http://www.yanganan.cn/server/about/aboutme.html">
                        <i class="fa fa-user"></i>
                        <span>About</span>
                    </a>
                    
                </nav>
                <a class="mobile-header-menu-button">
                    <i class="fa fa-bars"></i>
                </a>
            </div>
        </div>
        <div id="header-row">
            <div id="logo">
                <a href="/">
                    <img src="/images/logo.png" alt="logo">
                </a>
            </div>
            <div class="header-info">
                <div id="header-title">
                    
                    <h2>
                        杨 江
                    </h2>
                    
                </div>
                <div id="header-description">
                    
                    <h3>
                        海迷、爱运动、爱交友、爱旅行、喜欢接触新鲜事物、迎接新的挑战，更爱游离于错综复杂的编码与逻辑中
                    </h3>
                    
                </div>
            </div>
            <nav class="header-nav">
                <div class="social">
                    
                        <a title="Home" target="_blank" href="//yangchaojiang.cn">
                            <i class="fa fa-home fa-2x"></i></a>
                    
                        <a title="Github" target="_blank" href="//github.com/yangchaojiang">
                            <i class="fa fa-github fa-2x"></i></a>
                    
                        <a title="Weibo" target="_blank" href="//weibo.com/u/5114674051?topnav=1&wvr=6&topsug=1&is_all=1">
                            <i class="fa fa-weibo fa-2x"></i></a>
                    
                        <a title="Mail" target="_blank" href="mailto:yangchaojiang@outlook.com">
                            <i class="fa fa-envelope-o fa-2x"></i></a>
                    
                        <a title="qq" target="_blank" href="//wpa.qq.com/msgrd?v=3&uin=1007181167&site=qq&menu=yes">
                            <i class="fa fa-qq fa-2x"></i></a>
                    
                </div>
            </nav>
        </div>
    </div>
</header>
      <div class="outer">
        <section id="main" class="body-wrap"><article id="post-livedata-blog" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="post-title" itemprop="name">
      Architecture_Components  LiveData 学习
    </h1>
    <div class="post-title-bar">
      <ul>
          
        <li>
          <i class="fa fa-calendar"></i>  2017-06-05
        </li>
        <li>
          <i class="fa fa-eye"></i>
          <span id="busuanzi_value_page_pv"></span>
        </li>
      </ul>
    </div>
  

          
      </header>
    
    <div class="article-entry post-content" itemprop="articleBody">
      
            
            <h2 id="LiveData"><a href="#LiveData" class="headerlink" title="LiveData"></a>LiveData</h2><p><a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>是数据保持器类的值和运算。<br>不像常规可见，LiveData该生命周期的应用程序组件，使得遵守者可以指定Lifecycle它在哪应注意观察。</p>
<p>注：实时为您导入Android项目添加组件你的项目。<br><a id="more"></a><br><a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a><br>认为遵守者在活跃状态中如果遵守者’sLifecycle是的STARTED作业代表RESUMED状态。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">public class LocationLiveData extends LiveData&lt;Location&gt; &#123;</div><div class="line">    private LocationManager locationManager;</div><div class="line"></div><div class="line">    private SimpleLocationListener listener = new SimpleLocationListener() &#123;</div><div class="line">        @Override</div><div class="line">        public void onLocationChanged(Location location) &#123;</div><div class="line">            setValue(location);</div><div class="line">        &#125;</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    public LocationLiveData(Context context) &#123;</div><div class="line">        locationManager = (LocationManager) context.getSystemService(</div><div class="line">                Context.LOCATI+-ON_SERVICE);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Override</div><div class="line">    protected void onActive() &#123;</div><div class="line">        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Override</div><div class="line">    protected void onInactive() &#123;</div><div class="line">        locationManager.removeUpdates(listener);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>有三个重要部分中的这种实现<a href="https://developer.android.google.cn/reference/android/location/Location.html" target="_blank" rel="external">Location</a>：</p>
<font color="##006666">onActive()</font>

<p>当该方法被称为 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>具有有源观察者。这意味着我们需要开始观测从设备的位置更新。</p>
<font color="##006666">onInactive()</font>

<p>当这种方法被称为 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>没有任何积极的观察员。<br>由于没有观察们监听，也没有理由保持连接到<a href="https://developer.android.google.cn/reference/android/location/LocationManager.html" target="_blank" rel="external">LocationManager</a>服务。这很重要，因为保持连接会消耗显著电池电量没有任何好处。</p>
<font color="##006666">setValue()</font>

<p>调用此方法将更新后的值 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>与实例观察员活动通知。<br>我们可以用新的<font color="##006666">LocationLiveData()</font> 如下所示：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyFragment</span> <span class="keyword">extends</span> <span class="title">LifecycleFragment</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onActivityCreated</span> <span class="params">(Bundle savedInstanceState)</span> </span>&#123;</div><div class="line">        LiveData&lt;Location&gt; myLocationListener = ...;</div><div class="line">        Util.checkUserStatus(result -&gt; &#123;</div><div class="line">            <span class="keyword">if</span> (result) &#123;</div><div class="line">                myLocationListener.addObserver(<span class="keyword">this</span>, location -&gt; &#123;</div><div class="line">                    <span class="comment">// update UI</span></div><div class="line">                &#125;);</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">&#125;  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>请注意，该<font color="##006666" size="3">addObserver()</font>方法通过了 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LifecycleOwner.html" target="_blank" rel="external">LifecycleOwner</a>作为第一个参数。<br>这样做就表示该观察者应该绑定到 Lifecycle，意思是：</p>
</blockquote>
<ul>
<li><p>如果<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Lifecycle.html" target="_blank" rel="external">Lifecycle</a><br>处于激活状态不是（STARTED或RESUMED），观察者不叫即使该值的变化。</p>
</li>
<li><p>如果<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Lifecycle.html" target="_blank" rel="external">Lifecycle</a>被破坏，观察者被自动删除。</p>
</li>
</ul>
<p>这事实上<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a><br>是生命周期感知为我们提供了新的契机<br>：我们可以在多个活动，片段等之间的分享。为了保持我们的例子简单，我们可以按照如下使单：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LocationLiveData</span> <span class="keyword">extends</span> <span class="title">LiveData</span>&lt;<span class="title">Location</span>&gt; </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> LocationLiveData sInstance;</div><div class="line">    <span class="keyword">private</span> LocationManager locationManager;</div><div class="line"></div><div class="line">    <span class="meta">@MainThread</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> LocationLiveData <span class="title">get</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (sInstance == <span class="keyword">null</span>) &#123;</div><div class="line">            sInstance = <span class="keyword">new</span> LocationLiveData(context.getApplicationContext());</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> sInstance;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> SimpleLocationListener listener = <span class="keyword">new</span> SimpleLocationListener() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onLocationChanged</span><span class="params">(Location location)</span> </span>&#123;</div><div class="line">            setValue(location);</div><div class="line">        &#125;</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="title">LocationLiveData</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        locationManager = (LocationManager) context.getSystemService(</div><div class="line">                Context.LOCATION_SERVICE);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onActive</span><span class="params">()</span> </span>&#123;</div><div class="line">        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, <span class="number">0</span>, <span class="number">0</span>, listener);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onInactive</span><span class="params">()</span> </span>&#123;</div><div class="line">        locationManager.removeUpdates(listener);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>现在片段按如下方式使用它：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyFragment</span> <span class="keyword">extends</span> <span class="title">LifecycleFragment</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onActivityCreated</span> <span class="params">(Bundle savedInstanceState)</span> </span>&#123;</div><div class="line">        Util.checkUserStatus(result -&gt; &#123;</div><div class="line">            <span class="keyword">if</span> (result) &#123;</div><div class="line">                LocationLiveData.get(getActivity()).observe(<span class="keyword">this</span>, location -&gt; &#123;</div><div class="line">                   <span class="comment">// update UI</span></div><div class="line">                &#125;);</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>可能有多个片段和活动正在观察我们的<font color="##006666"> MyLocationListener</font>实例，<br>并 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>优雅地管理它们，使其连接到系统服务只有当他们中任何一个可见的（即活动）。</p>
<p>本<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>类提供了以下优点：</p>
<ul>
<li><p><font face="微软雅黑" weight="bold">没有内存泄漏:</font>由于Observers的束缚自己的Lifecycle对象，当他们被自动清除 Lifecycle被破坏。</p>
</li>
<li><p><font face="微软雅黑" weight="bold"> 没有崩溃，由于停止活动:</font>如果Observer的 Lifecycle是无效的（就像在后面堆栈的活动），他们将不会收到更改事件。</p>
</li>
<li><p><font face="微软雅黑" weight="bold">始终保持最新数据：</font>如果 Lifecycle再次开始（如活动可以追溯到从后面堆启动的状态），它接收到的最新位置数据（如果没有的话）。</p>
</li>
<li><p><font face="微软雅黑" weight="bold">适当的配置变化：</font>如果一个活动或片段由于重新创建到的配置改变（如设备旋转），它立即接收的最后一个可用Location的数据。</p>
</li>
<li><p><font face="微软雅黑" weight="bold">资源共享：</font>现在我们能保持的单个实例 MyLocationListener，连接到系统服务只有一次，并适当支持的应用程序的所有观察员。</p>
</li>
<li><p><font face="微软雅黑" weight="bold">没有更多的人工生命周期处理：</font>正如你可能已经注意到，我们的片段只是当它想，不担心被停止或启动停止后观察观察数据。LiveData 由于片段提供了自动管理所有的这 Lifecycle一边观察。</p>
</li>
</ul>
<h3 id="LiveData的转换"><a href="#LiveData的转换" class="headerlink" title="LiveData的转换"></a>LiveData的转换</h3><p>有时候，你可能希望更改 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>其派遣到观察员前值，<br>或者您可能需要返回不同的 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>基础上另外一个的值实例。</p>
<p>生命周期包提供了一个 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Transformations.html" target="_blank" rel="external">Transformations</a>，包含对这些操作的辅助方法</p>
<p><a href="&#39;https://developer.android.google.cn/reference/android/arch/lifecycle/Transformations.html#map(android.arch.lifecycle.LiveData&lt;X&gt;,%20android.arch.core.util.Function&lt;X, Y">Transformations.map()</a>‘)</p>
<p>在应用函数 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>值，和下游传播的结果。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">LiveData&lt;User&gt; userLiveData = ...;</div><div class="line">LiveData&lt;String&gt; userName = Transformations.map(userLiveData, user -&gt; &#123;</div><div class="line">    user.name + <span class="string">" "</span> + user.lastName</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p><a href="&#39;https://developer.android.google.cn/reference/android/arch/lifecycle/Transformations.html#switchMap(android.arch.lifecycle.LiveData&lt;X&gt;,%20android.arch.core.util.Function&lt;X,%20android.arch.lifecycle.LiveData&lt;Y&gt;">Transformations.switchMap()</a>‘)</p>
<p>类似于<a href="&#39;https://developer.android.google.cn/reference/android/arch/lifecycle/Transformations.html#map(android.arch.lifecycle.LiveData&lt;X&gt;,%20android.arch.core.util.Function&lt;X, Y">map()</a>‘)<br>,应用一个函数的值，并解开和下游调度的结果。传递给函数 <a href="&#39;https://developer.android.google.cn/reference/android/arch/lifecycle/Transformations.html#switchMap(android.arch.lifecycle.LiveData&lt;X&gt;,%20android.arch.core.util.Function&lt;X,%20android.arch.lifecycle.LiveData&lt;Y&gt;">switchMap()</a>‘)<br>必须返回 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Lifecycle.html" target="_blank" rel="external">Lifecycle</a>。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> LiveData&lt;User&gt; <span class="title">getUser</span><span class="params">(String id)</span> </span>&#123;</div><div class="line">  ...;</div><div class="line">&#125;</div><div class="line"></div><div class="line">LiveData&lt;String&gt; userId = ...;</div><div class="line">LiveData&lt;User&gt; user = Transformations.switchMap(userId, id -&gt; getUser(id) );</div></pre></td></tr></table></figure></p>
<p>使用这些转换允许结转观察者 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Lifecycle.html" target="_blank" rel="external">Lifecycle</a>对面，使得这些转换没有被计算，<br>除非一个观察者观察返回链路信息<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a><br>转换的这种懒惰的计算特性允许隐传下来的生命周期相关的行为，而不增加显式调用或依赖关系<br>每当你认为你需要 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Lifecycle.html" target="_blank" rel="external">Lifecycle</a>内部的对象ViewModel一、转化是可能的解决方案。</p>
<p>例如，我们假设一个UI，用户将在地址和他们的邮政编码的地址。<br>幼稚的<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a><br>对于这种UI可以像这样：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyViewModel</span> <span class="keyword">extends</span> <span class="title">ViewModel</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> PostalCodeRepository repository;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyViewModel</span><span class="params">(PostalCodeRepository repository)</span> </span>&#123;</div><div class="line">       <span class="keyword">this</span>.repository = repository;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> LiveData&lt;String&gt; <span class="title">getPostalCode</span><span class="params">(String address)</span> </span>&#123;</div><div class="line">       <span class="comment">// DON'T DO THIS</span></div><div class="line">       <span class="keyword">return</span> repository.getPostCode(address);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>如果是这样的实现中，UI将需要从之前的注销LiveData和重新登记，在每个时间实例新呼叫他们getPostalCode()。</p>
<p>此外，如果所述UI是重新创建，则它触发另一个调用repository.getPostCode()代替使用在先前呼叫的结果。</p>
<p>代替使用该方法时，可以实现如邮政编码信息一种变换地址的输入：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyViewModel</span> <span class="keyword">extends</span> <span class="title">ViewModel</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> PostalCodeRepository repository;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> MutableLiveData&lt;String&gt; addressInput = <span class="keyword">new</span> MutableLiveData();</div><div class="line">    <span class="keyword">public</span> <span class="keyword">final</span> LiveData&lt;String&gt; postalCode =</div><div class="line">            Transformations.switchMap(addressInput, (address) -&gt; &#123;</div><div class="line">                <span class="keyword">return</span> repository.getPostCode(address);</div><div class="line">             &#125;);</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="title">MyViewModel</span><span class="params">(PostalCodeRepository repository)</span> </span>&#123;</div><div class="line">      <span class="keyword">this</span>.repository = repository</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">setInput</span><span class="params">(String address)</span> </span>&#123;</div><div class="line">      addressInput.setValue(address);</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>请注意，我们还送了<b>postalCode</b>场 <b>public final</b>，因为它永远不会改变。</p>
</blockquote>
<p>它被定义为所述的变换<font color="##006666">addressInput</font>，使得当<font color="##006666">addressInpu</font>t变化，如果存在活动的观察者，<br> <font color="##006666">repository.getPostCode()</font>被调用。如果没有活动的观察员出席了通话的时间，也不执行计算，直到观察员加入。</p>
<p>这种机制允许应用水平较低，以创建 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>即是按需计算懒洋洋的对象。<br><a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>可以很容易地获得它们，在它们上面定义转换规则。</p>
<h3 id="创建新转换（Creating-new-transformations）"><a href="#创建新转换（Creating-new-transformations）" class="headerlink" title="创建新转换（Creating new transformations）"></a>创建新转换（Creating new transformations）</h3><p>有迹象表明，可能在你的应用程序非常有用十几个不同的特定的转换，但默认情况下不提供。为了实现自己的转型，</p>
<p>你可以使用 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/MediatorLiveData.html" target="_blank" rel="external">MediatorLiveData</a> 类，它是专门创建适当听取其他<a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a>实例，<br>通过它们发出的处理事件。<br><a href="https://developer.android.google.cn/reference/android/arch/lifecycle/MediatorLiveData.html" target="_blank" rel="external">MediatorLiveData</a> 需要关心到正确地传播其活动/非活动状态到所述源 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData.html" target="_blank" rel="external">LiveData</a><br>您可以检查执行 <a href="https://developer.android.google.cn/reference/android/arch/lifecycle/Transformations.html" target="_blank" rel="external">Transformations</a>的细节。</p>

            <div class="post-copyright">
    <div class="content">
        <p>最后更新： 2017年06月06日 18:59</p>
        <p>原始链接： <a class="post-url" href="/2017/06/05/livedata-blog/" title="Architecture_Components  LiveData 学习">http://yangchaojiang.cn/2017/06/05/livedata-blog/</a></p>
        <footer>
            <a href="http://yangchaojiang.cn">
                <img src="/images/logo.png" alt="杨朝江">
                杨朝江
            </a>
        </footer>
    </div>
</div>

      
    </div>
    <footer class="article-footer">
        
        
<div class="post-share">
    <a href="javascript:;" id="share-sub" class="post-share-fab">
        <i class="fa fa-share-alt"></i>
    </a>
    <div class="post-share-list" id="share-list">
        <ul class="share-icons">
          <li>
            <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yangchaojiang.cn/2017/06/05/livedata-blog/&title=《Architecture_Components  LiveData 学习》 — yangchaojiang&pic=http://yangchaojiang.cnimages/logo.png" data-title="微博">
              <i class="fa fa-weibo"></i>
            </a>
          </li>
          <li>
            <a class="weixin share-sns" id="wxFab" href="javascript:;" data-title="微信">
              <i class="fa fa-weixin"></i>
            </a>
          </li>
          <li>
            <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yangchaojiang.cn/2017/06/05/livedata-blog/&title=《Architecture_Components  LiveData 学习》 — yangchaojiang&source=LiveDataLiveData是数据保持器类的值和运算。不像常规可见，LiveData该生命周期的应用程序组件，使得遵守者可以指定Lifecycle它在..." data-title="QQ">
              <i class="fa fa-qq"></i>
            </a>
          </li>
          <li>
            <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yangchaojiang.cn/2017/06/05/livedata-blog/" data-title="Facebook">
              <i class="fa fa-facebook"></i>
            </a>
          </li>
          <li>
            <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Architecture_Components  LiveData 学习》 — yangchaojiang&url=http://yangchaojiang.cn/2017/06/05/livedata-blog/&via=http://yangchaojiang.cn" data-title="Twitter">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li>
            <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yangchaojiang.cn/2017/06/05/livedata-blog/" data-title="Google+">
              <i class="fa fa-google-plus"></i>
            </a>
          </li>
        </ul>
     </div>
</div>
<div class="post-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;" id="wxShare-close">×</a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://yangchaojiang.cn/2017/06/05/livedata-blog/" alt="微信分享二维码">
</div>

<div class="mask"></div>

        
        <ul class="article-footer-menu">
            
            
  <li class="article-footer-tags">
    <i class="fa fa-tags"></i>
      
    <a href="/tags/Architecture_Components/" class="color4">Architecture_Components</a>
      
    <a href="/tags/LiveData/" class="color4">LiveData</a>
      
  </li>

        </ul>
        
    </footer>
  </div>
</article>


    <aside class="post-toc-pos post-toc-top" id="post-toc">
        <nav class="post-toc-wrap">
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#LiveData"><span class="post-toc-text">LiveData</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#LiveData的转换"><span class="post-toc-text">LiveData的转换</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#创建新转换（Creating-new-transformations）"><span class="post-toc-text">创建新转换（Creating new transformations）</span></a></li></ol></li></ol>
        </nav>
    </aside>
    

<nav id="article-nav">
  
    <a href="/2017/06/05/room-blod/" id="article-nav-newer" class="article-nav-link-wrap">

      <span class="article-nav-title">
        <i class="fa fa-hand-o-left" aria-hidden="true"></i>
        
          Architecture_Components Room Persistence
        
      </span>
    </a>
  
  
    <a href="/2017/06/04/architecture/" id="article-nav-older" class="article-nav-link-wrap">
      <span class="article-nav-title">google 新出开发应用架构 Architecture Components ( Lifecycles LiveDatra Room) 组件架构，目前公开测试阶段</span>
      <i class="fa fa-hand-o-right" aria-hidden="true"></i>
    </a>
  
</nav>



    
        <div id="SOHUCS" sid="livedata-blog" ></div>
<script type="text/javascript">
    (function(){
        var appid = 'cyt36tWXs';
        var conf = '42b79e0329709ef48318d7d6739122c2';
        var width = window.innerWidth || document.documentElement.clientWidth;
        if (width < 960) {
            window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    
</section>
        
      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info" class="inner">
      
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


      <p>
        Powered by  <a href="http://hexo.io/" target="_blank">Hexo</a>
        Theme <a href="//github.com/wongminho/hexo-theme-miho" target="_blank">MiHo</a>
      &copy; 2018 杨朝江<br>
      </p>
    </div>
  </div>
</footer>
    <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  var mihoConfig = {
      root: "http://yangchaojiang.cn",
      animate: true,
      isHome: false,
      share: true
  }
</script>
<div class="sidebar">
    <div id="sidebar-search" title="Search">
        <i class="fa fa-search"></i>
    </div>
    <div id="sidebar-category" title="Categories">
        <i class="fa fa-book"></i>
    </div>
    <div id="sidebar-tag" title="Tags">
        <i class="fa fa-tags"></i>
    </div>
    <div id="sidebar-top">
        <span class="sidebar-top-icon"><i class="fa fa-angle-up"></i></span>
    </div>
</div>
<div class="sidebar-menu-box" id="sidebar-menu-box">
    <div class="sidebar-menu-box-container">
        <div id="sidebar-menu-box-categories">
            
        </div>
        <div id="sidebar-menu-box-tags">
            <a href="/tags/Android-Kotlin/" style="font-size: 10px;">-Android -Kotlin</a> <a href="/tags/Android/" style="font-size: 20px;">Android</a> <a href="/tags/Architecture-Components/" style="font-size: 10px;">Architecture Components</a> <a href="/tags/Architecture-Components/" style="font-size: 13.33px;">Architecture_Components</a> <a href="/tags/Gradle/" style="font-size: 10px;">Gradle</a> <a href="/tags/Kotlin/" style="font-size: 16.67px;">Kotlin</a> <a href="/tags/LiveData/" style="font-size: 10px;">LiveData</a> <a href="/tags/Room/" style="font-size: 10px;">Room</a> <a href="/tags/java/" style="font-size: 13.33px;">java</a> <a href="/tags/kotlin/" style="font-size: 10px;">kotlin</a> <a href="/tags/lambda/" style="font-size: 10px;">lambda</a> <a href="/tags/leficycle/" style="font-size: 10px;">leficycle</a>
        </div>
    </div>
    <a href="javascript:;" class="sidebar-menu-box-close">&times;</a>
</div>
<div class="mobile-header-menu-nav" id="mobile-header-menu-nav">
    <div id="mobile-header-menu-container">
        <span class="title">Menu</span>
        <ul class="mobile-header-menu-navbar">
            
            <li>
                <a target="_blank" href="//yanganan.cn">
                    <i class="fa fa-home"></i><span>Home</span>
                </a>
            </li>
            
            <li>
                <a  href="/archives">
                    <i class="fa fa-archive"></i><span>Archives</span>
                </a>
            </li>
            
            <li>
                <a target="_blank" href="http://www.yanganan.cn/server/about/aboutme.html">
                    <i class="fa fa-user"></i><span>About</span>
                </a>
            </li>
            
        </ul>
    </div>
</div>
<div class="search-wrap">
    <span class="search-close">&times;</span>
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
            <i class="icon icon-lg icon-chevron-left"></i>
        </a>
        <input class="search-field" placeholder="Search..." id="keywords">
        <a id="search-submit" href="javascript:;">
            <i class="fa fa-search"></i>
        </a>
    <div class="search-container" id="search-container">
        <ul class="search-result" id="search-result">
        </ul>
    </div>
</div>

<div id="search-tpl">
    <li class="search-result-item">
        <a href="{url}" class="search-item-li">
            <span class="search-item-li-title" title="{title}">{title}</span>
        </a>
    </li>
</div>
<script src="/js/search.js"></script>
<script src="/js/main.js"></script>


  <script src="//cdn.bootcss.com/particles.js/2.0.0/particles.min.js"></script>
  <div id="particles"></div>
  <script src="/js/particles.js"></script>







  <link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css">
  <script src="//cdn.bootcss.com/scrollReveal.js/3.0.5/scrollreveal.js"></script>
  <script src="/js/animate.js"></script>

  </div>
</body>
</html>